package com.kangye.learnteacher.util;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/*
 * 下载工具类
 * @author make Java
 * @data 2021-5-18 20:38:24
 * */
@Component
public class DownloadFileUtil {

    /*
     * @Description
     * 从前台获取的查询条件
     * @pageNum 当前页
     * @pageSize 每页条数
     * */
    public void download(ClassPathResource cpr, String fileName, HttpServletResponse resp) {
        try {
            InputStream is = cpr.getInputStream();
            Workbook workbook = new XSSFWorkbook(is);
            //设置编码格式
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("application/binary;charset=ISO8859-1");
            resp.setHeader("content-Type", "application/vnd.ms-excel");
            //设置附加文件名
            resp.setHeader("Content-Disposition",
                    "attachment;filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
            workbook.write(resp.getOutputStream());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
